package com.hzncc.scaffold.controller.Rear.User;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.github.pagehelper.PageInfo;
import com.hzncc.scaffold.core.ResultT;
import com.hzncc.scaffold.entity.Other.User;
import com.hzncc.scaffold.entity.Vo.AddSubAdminVo;
import com.hzncc.scaffold.entity.Vo.SubAdminVo;
import com.hzncc.scaffold.entity.Vo.UpdateSubAdminVo;
import com.hzncc.scaffold.entity.Vo.UserIdVo;
import com.hzncc.scaffold.mapper.UserMapper;
import com.hzncc.scaffold.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

/**
 * @Author: DrunkBear
 * @Date: 2022-06-20 17:50
 * @Description: null
 */
@Api(tags = "用户管理-子管理员")
@RequestMapping("/manage/admin")
@RestController
public class SubAdminController {

    @Autowired
    UserMapper userMapper;

    @Autowired
    UserService userService;


    @GetMapping("/list")
    @ApiOperation("子管理员列表")
    public ResultT list(Integer pageNum, Integer pageSize, String keyword) {
        List<SubAdminVo> subAdminVos = userService.listSubAdmin(pageNum, pageSize, keyword);
        HashMap<String,Object> map = new HashMap<>();
        map.put("rows",subAdminVos);
        map.put("count",new PageInfo<>(subAdminVos).getTotal());

        return ResultT.success(map);
    }


    @PostMapping("/delete")
    @ApiOperation("删除子管理员")
    public ResultT delete(@RequestBody UserIdVo userIdVo) {
        Integer userId = userIdVo.getUserId();

        if (userService.getById(userId) == null) {
            return ResultT.fail("数据错误");
        }

        User user = userService.getById(userId);
        user.setIsDelete(true);
        boolean update = userService.updateById(user);

        if (update) {
            return ResultT.success("操作成功");
        } else {
            return ResultT.fail("删除失败");
        }
    }

    @PostMapping("/update")
    @ApiOperation("修改子管理员")
    public ResultT update(@RequestBody UpdateSubAdminVo updateSubAdminVo) {
        Integer userId = updateSubAdminVo.getUserId();

        if (userService.getById(userId) == null) {
            return ResultT.fail("数据错误");
        }

        User user = BeanUtil.copyProperties(updateSubAdminVo, User.class, "routeAuth");
        StringBuilder routeAuth = new StringBuilder();
        List<String> routeAuthList = updateSubAdminVo.getRouteAuth();
        for (String route : routeAuthList) {
            routeAuth.append(route).append(",");
        }
        routeAuth = new StringBuilder(StrUtil.removeSuffix(routeAuth.toString(), ","));

        user.setRouteAuth(routeAuth.toString());
        user.setId(updateSubAdminVo.getUserId());

        boolean update = userService.updateById(user);

        if (update) {
            return ResultT.success("修改成功");
        } else {
            return ResultT.fail("修改失败");
        }
    }


    @PostMapping("/add")
    @ApiOperation("新增子管理员")
    public ResultT add(@RequestBody AddSubAdminVo addSubAdminVo) {
        User user = BeanUtil.copyProperties(addSubAdminVo, User.class, "routeAuth");

        StringBuilder routeAuth = new StringBuilder();
        List<String> routeAuthList = addSubAdminVo.getRouteAuth();
        for (String route : routeAuthList) {
            routeAuth.append(route).append(",");
        }
        routeAuth = new StringBuilder(StrUtil.removeSuffix(routeAuth.toString(), ","));

        user.setRouteAuth(routeAuth.toString());
        user.setCreateTime(DateUtil.date());

        //子管理员默认密码 12345678
        String gensalt = BCrypt.gensalt();
        String hashpw = BCrypt.hashpw("12345678", gensalt);

        user.setInfo("");
        user.setRole("子管理员");
        user.setPassword(hashpw);
        boolean save = userService.save(user);

        if (save) {
            return ResultT.success("操作成功");
        } else {
            return ResultT.fail("操作失败");
        }
    }

    @GetMapping("/exportAdmin")
    @ApiOperation("导出子管理员")
    public void exportAdmin(HttpServletResponse response) throws IOException {
        List<SubAdminVo> subAdminVos = userService.listSubAdmin(null, null, null);
        ArrayList<Map<String, Object>> exportSubAdminVos = new ArrayList<>();

        for (SubAdminVo subAdminVo : subAdminVos) {
            LinkedHashMap<String, Object> map = new LinkedHashMap<>();
            map.put("子管理员姓名", subAdminVo.getName());
            map.put("账号", subAdminVo.getAccount());
            map.put("联系地址", subAdminVo.getAddress());
            if (subAdminVo.getTelephone() != null) {
                map.put("联系电话", subAdminVo.getTelephone());
            }
            map.put("创建时间", subAdminVo.getCreateTime());
            if (subAdminVo.getStatus() == 0) {
                map.put("状态", "正常");
            } else {
                map.put("状态", "冻结");
            }
            exportSubAdminVos.add(map);
        }
        if (CollUtil.isNotEmpty(exportSubAdminVos)) {
            ExcelWriter writer = ExcelUtil.getWriter();
            writer.write(exportSubAdminVos, true);
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            String fileName = URLEncoder.encode("子管理员列表" + ".xls", "UTF-8");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            ServletOutputStream out = response.getOutputStream();
            writer.flush(out);
            writer.close();
        }

    }
}
